package im.starchat.chat.activity.publish;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.format.Time;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;
import com.squareup.picasso.Picasso;

import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import im.starchat.chat.R;
import im.starchat.chat.XLApplication;
import im.starchat.chat.activity.BaseActivity;
import im.starchat.chat.control.QavsdkControl;
import im.starchat.chat.rest.RestClient;
import im.starchat.chat.rest.model.PreviewBean;
import im.starchat.chat.rest.model.UserInfo;
import im.starchat.chat.rest.model.api.UpTokenResponse;
import im.starchat.chat.utils.BitmapHelp;
import im.starchat.chat.utils.FileUtils;
import im.starchat.chat.utils.ImageConstant;
import im.starchat.chat.utils.ImageUtil;
import im.starchat.chat.utils.PreferencesStorageUtil;
import im.starchat.chat.utils.UserUtils;
import im.starchat.chat.view.PickView;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

/**
 * 发布预告的界面
 */
public class ReleaseParadeActivity extends BaseActivity implements TextWatcher, View.OnClickListener {
    private static final String TAG = "ReleaseParadeActivity";
    private int year;
    private int month;
    private int day;
    private int hour;
    private int minute;
    private int today;
    private String startTime;
    private int isTomorrow = 0;
    private boolean isOnce = true;

    private LinearLayout mLinearLayout;
    private View timePickerView;
    private TextView mTextViewParadeTime;
    private TextView mTextViewParadeRemainingTime;
//    private ImageButton mImageButtonParadeCover;
//    private ImageButton mImageButtonCloseParadeCover;
    private String paradeTitle;
    private EditText mEditTextParadeTitle;
    private Button mButtonTimeOk;
    private Button mButtonReleaseParade;
    private String paradeCoverPath;
    private Context ctx = null;
    private QavsdkControl mQavsdkControl;
    private UserInfo mSelfUserInfo;

    @InjectView(R.id.parade_live_cover)
    ImageView mCoverImg;
    @InjectView(R.id.set_background)
    TextView mSetBackgroundBtn;
    @InjectView(R.id.close)
    ImageView mCloseBtn;
    File mFile;
    private Uri mCameraImageUri, mImageUri;

    // 设置头像
    private final static int SELECT_PIC_KITKAT = 3;
    private final static int SELECT_PIC = 4;
    private final static int REQ_CODE_PHOTO_CROP = 5;
    private final static int REQ_CODE_CAMERA = 6;
    private static final String SAVE_AVATORNAME = "parade.jpeg";// 保存的图片名

    private String mImageKey = "";


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.release_parade_activity);
        ButterKnife.inject(this);
        initData();
        initViewUI();
    }

    private void initData() {
        File galleryFile = new File(XLApplication.catchDir + "/" + "icon"
                + new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date()));
        mImageUri = Uri.fromFile(galleryFile);

        File cameraFile = new File(XLApplication.cameraDir, new SimpleDateFormat("yyyyMMdd-HHmmss")
                .format(new Date()) + ".jpg");
        mCameraImageUri = Uri.fromFile(cameraFile);
    }

    private void initViewUI() {

        if(!TextUtils.isEmpty(UserUtils.getUserInstance().getAvatar())){
            Picasso.with(ReleaseParadeActivity.this).load(UserUtils.getUserInstance().getAvatar())
                    .placeholder(R.drawable.home_bg)
                    .into(mCoverImg);

        }
        mLinearLayout = (LinearLayout)findViewById(R.id.parade_layout);
        mTextViewParadeTime = (TextView) findViewById(R.id.parade_time);
        mTextViewParadeRemainingTime = (TextView) findViewById(R.id.remaining_time);
        mEditTextParadeTitle = (EditText) findViewById(R.id.parade_live_title);
        mEditTextParadeTitle.addTextChangedListener(this);
        mButtonReleaseParade = (Button) findViewById(R.id.btn_release_parade);
//        mImageButtonParadeCover = (ImageButton) findViewById(R.id.parade_live_cover);
//        mImageButtonCloseParadeCover = (ImageButton) findViewById(R.id.close_parade_live_cover);
        mButtonReleaseParade.setOnClickListener(this);
//        mImageButtonParadeCover.setOnClickListener(this);
//        mImageButtonCloseParadeCover.setOnClickListener(this);
        mTextViewParadeTime.setOnClickListener(this);
        mTextViewParadeRemainingTime.setOnClickListener(this);
        mSetBackgroundBtn.setOnClickListener(this);
        mCloseBtn.setOnClickListener(this);

        if(UserUtils.getUserInstance() != null && !TextUtils.isEmpty(UserUtils.getUserInstance().getAvatar())){
            Picasso.with(ReleaseParadeActivity.this).load(UserUtils.getUserInstance().getAvatar())
                    .placeholder(R.drawable.channel_bg)
                    .into(mCoverImg);
        }

        ctx = this;
        XLApplication mXLApplication = (XLApplication)getApplication();
        mQavsdkControl = mXLApplication.getQavsdkControl();
        mSelfUserInfo = mXLApplication.getMyselfUserInfo();
        mImageKey = PreferencesStorageUtil.getUserId(ReleaseParadeActivity.this) + System.currentTimeMillis() + ".jpg";
        paradeCoverPath = ImageConstant.ROOT_DIR + mImageKey;


        Time time = new Time();
        time.setToNow();
        year = time.year;
        month = time.month + 1;
        today = day = time.monthDay;
        hour = time.hour;
        minute = time.minute;
    }

    @Override
    public void onClick(View v) {
//        String coverName = null;
        switch (v.getId()) {
            case R.id.set_background:
//                coverName = "tempImage1.jpg";
//                takePhoto(coverName);
                onUserImageClick();
                break;
            case R.id.btn_release_parade:
                onReleaseParade();
                break;
            case R.id.parade_time:
            case R.id.remaining_time:
                if(isOnce) {
                    onTimePicker();
                    mButtonReleaseParade.setVisibility(View.GONE);
                    isOnce = false;
                }
                Log.d(TAG, "time");
                break;
            case R.id.btn_parade_time_ok:
                isOnce = true;
                settingParadeTime();
                settingRemainingTime();
                mLinearLayout.removeView(timePickerView);
                mButtonTimeOk.setVisibility(View.GONE);
                mButtonReleaseParade.setVisibility(View.VISIBLE);
                break;
            case R.id.close:
                finish();
                break;

//            case R.id.close_parade_live_cover:
//                mImageButtonCloseParadeCover.setVisibility(View.GONE);
//                Drawable drawable = getResources().getDrawable(R.drawable.release_cover);
//                mCoverImg.setImageDrawable(drawable);
//                break;
            default:
                break;
        }
    }

    private void onUserImageClick() {
        if(FileUtils.isSDCardMounted()){
            showOptionsDialog();
        }else{
            toast("没有安装SD卡!", Toast.LENGTH_SHORT);
        }
    }

    // 选择图片来源
    private void showOptionsDialog()
    {
        String[] items = new String[] { "拍照", "选择本地图片" };

        DialogInterface.OnClickListener click = new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                switch (which)
                {
                    case 0://拍照
                        Intent camera = new Intent("android.media.action.IMAGE_CAPTURE");
                        camera.putExtra("output", mCameraImageUri);
                        startActivityForResult(camera, REQ_CODE_CAMERA);
                        break;
                    case 1://选择本地图片

                        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
                            Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
                            intent.addCategory(Intent.CATEGORY_OPENABLE);
                            intent.setType("image/jpeg");
                            startActivityForResult(intent, SELECT_PIC_KITKAT);
                        } else {
                            Intent intent = new Intent();
                            intent.setType("image/*");
                            intent.setAction(Intent.ACTION_GET_CONTENT);
                            startActivityForResult(intent, SELECT_PIC);
                        }
                        break;
                }
            }
        };

        new AlertDialog.Builder(this).setItems(items,
                click).show();
    }


    private void getUserHeadImage() {
        File outputImage = new File(Environment.getExternalStorageDirectory(), "output.jpg");
        File destDir = new File(ImageConstant.ROOT_DIR);
        if (!destDir.exists()) {
            destDir.mkdirs();
        }
        try {
            if (outputImage.exists()) {
                outputImage.delete();
            }
            outputImage.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }

        ImageConstant.imageuri = Uri.fromFile(outputImage);
        Intent intent = new Intent("android.intent.action.PICK");
        intent.setType("image/*");
        intent.putExtra("crop", true);
        intent.putExtra("scale", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, ImageConstant.imageuri);
        startActivityForResult(intent, ImageConstant.SELECT_PHOTO);
    }


    public void onTimePicker() {
//        mButtonTimeOk.setVisibility(View.VISIBLE);
        LayoutInflater layoutInflater = LayoutInflater.from(this);
        timePickerView = layoutInflater.inflate(R.layout.time_picker, null);
        mButtonTimeOk = (Button) timePickerView.findViewById(R.id.btn_parade_time_ok);

        mButtonTimeOk.setOnClickListener(this);

        PickView hour_pv = (PickView) timePickerView.findViewById(R.id.hour_pv);
        PickView minute_pv = (PickView) timePickerView.findViewById(R.id.minute_pv);
        PickView day_pv = (PickView) timePickerView.findViewById(R.id.day_pv);

        List<String> hours = new ArrayList<String>();
        List<String> minutes = new ArrayList<String>();
        List<String> days = new ArrayList<String>();

        days.add("明天");
        days.add("今天");

        for (int i = 0; i < 24; i++) {
            hours.add(i < 10 ? "0" + i : "" + i);
        }

        for (int i = 0; i < 60; i++) {
            minutes.add(i < 10 ? "0" + i : "" + i);
        }

        hour_pv.setData(hours, hour);
        hour_pv.setOnSelectListener(new PickView.onSelectListener() {
            @Override
            public void onSelect(String text) {
                ReleaseParadeActivity.this.hour = Integer.parseInt(text);
            }
        });
        minute_pv.setData(minutes, minute);
        minute_pv.setOnSelectListener(new PickView.onSelectListener() {
            @Override
            public void onSelect(String text) {
                ReleaseParadeActivity.this.minute = Integer.parseInt(text);
            }
        });

        day_pv.setData(days, isTomorrow == 1 ? 0:1);

        day_pv.setOnSelectListener(new PickView.onSelectListener() {
            @Override
            public void onSelect(String text) {
                if (text.equals("明天")) {
                    if(today == day)
                        day++;
                    isTomorrow = 1;
                } else {
                    if(today != day)
                        day--;
                    isTomorrow = 0;
                }
            }
        });

        LinearLayout.LayoutParams timePickerViewParams = new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, 460);
//        timePickerViewParams.leftMargin = 140;
        timePickerView.setLayoutParams(timePickerViewParams);
        mLinearLayout.addView(timePickerView);
    }

    public void swapDays() {
        if (isTomorrow == 1) {
            int dayOfMonth[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
            if (isleepyear()) {
                dayOfMonth[2] = 29;
            }

            //处理日月变换
            if(day == 0) {
                month--;
                day = dayOfMonth[month];
            } else if (day  == dayOfMonth[month] + 1) {
                day = 1;
                month++;
            }

            //处理月年变换（元旦）
            if(month == 0) {
                year--;
                month = 12;
            }else if (month == 13) {
                month = 1;
                year++;
            }
        }
    }

    private boolean isleepyear() {
        if ((year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0))
            return true;
        return false;
    }

    private void settingParadeTime() {
        String showMonth = null;
        String showDay = null;
        String showHour = null;
        String showMinute = null;
        swapDays();
        if (month < 10) {
            showMonth = "0" + month;
        } else {
            showMonth = "" + month;
        }

        if (day < 10) {
            showDay = "0" + day;
        } else {
            showDay = "" + day;
        }

        if (hour < 10) {
            showHour = "0" + hour;
        } else {
            showHour = "" + hour;
        }

        if (minute < 10) {
            showMinute = "0" + minute;
        } else {
            showMinute = "" + minute;
        }

        //startTime = "" + year + "-"
        startTime = "" + showMonth + "-"
                + showDay + " "
                + showHour + ":"
                + showMinute;
        mTextViewParadeTime.setText(startTime);

    }

    private void settingRemainingTime() {
        int remainingHour;
        int remainingMinute;
        String remainingTime = "";
        Time time = new Time();
        time.setToNow();

        if(isTomorrow == 1) {
            remainingHour = 24 - time.hour + hour;
            remainingMinute = (60 - time.minute + minute) % 60;
        } else {
            remainingHour = hour - time.hour;
            if(remainingHour > 0)
                remainingMinute = (60 - time.minute + minute) % 60;
            else
                remainingMinute = minute - time.minute;
        }

        if(remainingHour > 0) {
            remainingTime = "" + remainingHour + "小时";
            if(remainingMinute > 0) {
                remainingTime += remainingMinute + "分钟后";
            } else {
                remainingTime += "后";
            }
            mButtonReleaseParade.setEnabled(true);
        } else if(remainingHour == 0){
            if(remainingMinute > 0) {
                remainingTime += remainingMinute + "分钟后";
                mButtonReleaseParade.setEnabled(true);
            } else if(remainingMinute == 0) {
                mButtonReleaseParade.setEnabled(true);
                remainingTime = "立即直播";
            } else {
                mButtonReleaseParade.setEnabled(false);
                remainingTime = "时间已过，请重设";
            }
        } else {
            mButtonReleaseParade.setEnabled(false);
            remainingTime = "时间已过!请重设";
        }

        toast(remainingTime, Toast.LENGTH_SHORT);
//        mTextViewParadeRemainingTime.setText(remainingTime);
    }

    public void onReleaseParade() {
        releaseParade();
    }

    public void releaseParade() {

        if(TextUtils.isEmpty(paradeTitle)){
            paradeTitle = mEditTextParadeTitle.getHint().toString();
        }

        if(hasPic){
            XLApplication.getInstance().getRestClient().upToken("preview/" + mImageKey, new Callback<UpTokenResponse>() {
                @Override
                public void success(UpTokenResponse nullResponse, Response response) {

                    UploadManager uploadManager = new UploadManager();
                    uploadManager.put(paradeCoverPath, "preview/" + mImageKey, nullResponse.getUptoken(),
                            new UpCompletionHandler() {
                                @Override
                                public void complete(String key, ResponseInfo info, JSONObject response) {

                                    Log.d(TAG, "key--->" + key);
                                    Log.d(TAG, "ResponseInfo--->" + info.statusCode);
                                    Log.d(TAG, "response--->" + response.toString());

                                    XLApplication.getInstance().getRestClient().postPreviews(paradeTitle, "" + year + "-" + startTime + ":00", RestClient.BASE_IMG_URL + key, new Callback<PreviewBean>(){
                                        @Override
                                        public void success(PreviewBean previewsBean, Response response) {
                                            toast("发布预告成功", Toast.LENGTH_SHORT);
                                            finish();
                                        }

                                        @Override
                                        public void failure(RetrofitError error) {
                                            toast("发布预告失败", Toast.LENGTH_SHORT);
                                            finish();
                                        }
                                    });
//                                    Log.i("qiniu", info);
                                }
                            }, null);
                }

                @Override
                public void failure(RetrofitError error) {

                }
            });
        }else{
            XLApplication.getInstance().getRestClient().postPreviews(paradeTitle, "" + year + "-" + startTime + ":00", UserUtils.getUserInstance().getAvatar(), new Callback<PreviewBean>(){
                @Override
                public void success(PreviewBean previewsBean, Response response) {
                    toast("发布预告成功", Toast.LENGTH_SHORT);
                    finish();
                }

                @Override
                public void failure(RetrofitError error) {
                    toast("发布预告失败", Toast.LENGTH_SHORT);
                    finish();
                }
            });
        }




//
//
//        new Thread() {
//            @Override
//            public void run() {
//                super.run();
//                JSONObject object = new JSONObject();
//                try {
//                    object.put(Util.EXTRA_LIVE_TITLE, paradeTitle);
//                    object.put(Util.EXTRA_USER_PHONE, mSelfUserInfo.getUserPhone());
//                    object.put("starttime", "" + year + "-" + startTime + ":00");
//                    object.put("imagetype", 2);
//                    System.out.println(object.toString());
//                    ImageUtil tool = new ImageUtil();
//                    String url = "http://203.195.167.34/live_forcastcreate.php";
//                    int ret = tool.sendCoverToServer(paradeCoverPath, object, url, "forcastdata");
//                    Log.d(TAG, "testhere" + " " + ret);
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                } catch (UnsupportedEncodingException e) {
//                    e.printStackTrace();
//                }
//            }
//        }.start();
    }

    boolean hasPic = false;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.d(TAG, "return:" + requestCode + " " + resultCode);
        switch (requestCode) {


            case SELECT_PIC_KITKAT:
                // 从相册返回
                Uri localUri = data.getData();
                if (localUri == null) {
                    return;
                }
                String path = BitmapHelp.getPath(this, localUri);
                System.out.println("SELECT_PIC_KITKAT--path->" + path);
                if(!TextUtils.isEmpty(path)){
                    Uri uri = Uri.fromFile(new File(path));
                    readLocalImage(uri);
                }

                break;
            case SELECT_PIC:
                // 从相册返回
                Uri mUri = data.getData();
                System.out.println("SELECT_PIC_KITKAT--mUri->" + mUri.getAuthority() + "   " +  mUri.getPath());
                if (mUri == null) {
                    return;
                }
                readLocalImage(mUri);
                break;
            case REQ_CODE_CAMERA:
                // 从相机返回,从设置相机图片的输出路径中提取数据
                readLocalImage(mCameraImageUri);
                break;
            case REQ_CODE_PHOTO_CROP:
                System.out.println("REQ_CODE_PHOTO_CROP--mImageUri.getPath()-> " + mImageUri.getPath());
                Bitmap bitmap = BitmapFactory.decodeFile(mImageUri.getPath());
                saveMyBitmap(bitmap);
                System.out.println("REQ_CODE_PHOTO_CROP--bitmap-> " + (bitmap == null));
                hasPic = true;
                mCoverImg.setImageBitmap(bitmap);
                break;

            default:
                break;
        }
    }

    /**
     * 将头像保存在SDcard
     */
    public void saveMyBitmap(Bitmap bitmap)
    {
        if(FileUtils.createOrExistsFolder(ImageUtil.getImageCachePath())){
            File f = new File(ImageUtil.getImageCachePath(),
                    SAVE_AVATORNAME);
            try
            {
                f.createNewFile();
                FileOutputStream fOut = new FileOutputStream(f);
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);

                fOut.flush();
                fOut.close();
                mFile = f;
            } catch (IOException e)
            {
                e.printStackTrace();
            }
        }

    }

    private void readLocalImage(Uri uri) {
        if (uri != null) {
            startPhotoCrop(uri, REQ_CODE_PHOTO_CROP); // 图片裁剪
        }
    }

    private void startPhotoCrop(Uri uri, int reqCode) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // crop为true是设置在开启的intent中设置显示的view可以剪裁
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX,outputY 是剪裁图片的宽高
        intent.putExtra("outputX", 600);
        intent.putExtra("outputY", 600);
        intent.putExtra("output", mImageUri);
        intent.putExtra("return-data", false);
        intent.putExtra("noFaceDetection", true);
        startActivityForResult(intent, reqCode);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    public void takePhoto(String name) {
        File outputImage = new File(Environment.getExternalStorageDirectory(), name);
        ImageConstant.PhotoClassflag = ImageConstant.COVER;
        File destDir = new File(ImageConstant.ROOT_DIR);
        if (!destDir.exists()) {
            destDir.mkdirs();
        }
        try {
            if (outputImage.exists()) {
                outputImage.delete();
            }
            outputImage.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        ImageConstant.imageuri = Uri.fromFile(outputImage);
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, ImageConstant.imageuri);
        startActivityForResult(intent, ImageConstant.TAKE_PHOTO);
    }

    public void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 800);
        intent.putExtra("outputY", 800);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, ImageConstant.CROP_PHOTO);
    }

    @Override
    public void afterTextChanged(Editable s) {
        paradeTitle = mEditTextParadeTitle.getText().toString();
//        mButtonReleaseParade.setEnabled(paradeTitle != null && paradeTitle.length() > 0);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
    }
}
